﻿/// <reference path="Settings.js" />
/// <reference path="Requester.js" />
/// <reference path="UI.js" />

(function () {
    //"use strict";

    var list = new WinJS.Binding.List();
    var groupedItems = list.createGrouped(
        function groupKeySelector(item) { return item.group.key; },
        function groupDataSelector(item) { return item.group; }
    );


    WinJS.Namespace.define("Data", {
        items: groupedItems,
        groups: groupedItems.groups,
        getItemReference: getItemReference,
        getItemsFromGroup: getItemsFromGroup,
        resolveGroupReference: resolveGroupReference,
        resolveItemReference: resolveItemReference,
        Manager: WinJS.Class.define(function(){

        },
        {},
        {
            refreshRSS: function () {
                while (list.length > 0) {
                    list.pop();
                }

                generateData()
                    .then(
                    function (itms) {
                        while (list.length > 0) {
                            list.pop();
                        }
                        itms.forEach(function (item) {
                            list.push(item);
                        });

                        list.notifyReload();
                    },
                    function (error) {
                        list.push(Data.Manager.errorItem);
                        list.notifyReload();
                        UI.alert("Couldn't load RSS! Try fix your RSS settings!");
                    });
            },
            defaultRssGroupOld: {
                key: "0",
                title: "Sportni.bg",
                subtitle: "Известни още като спирни.бг :)",
                backgroundImage: "http://www.sportni.bg/images/sportniLogo.png",
                description: "Български спортен сайт!",
                url: "http://www.sportni.bg/rss.php?c=10",
                itemInfo: {
                    tagName: "item",
                    title: { prefix: "", tagName: "title", attributeName: "" },
                    subtitle: { prefix: "Date: ", tagName: "pubDate", attributeName: "" },
                    description: { prefix: "Author: ", tagName: "author", attributeName: "" },
                    content: { prefix: "", tagName: "description", attributeName: "" },
                    moreInfo: { tagName: "link", attributeName: ""},
                    image: { tagName: "enclosure", attributeName: "url" },
                },
            },
            defaultRssGroup: {
                "key": "0",
                "title": "Uefa.com",
                "subtitle": "UEFA official cite news",
                "backgroundImage": "http://img.uefa.com/imgml/rssheader.gif",
                "url": "http://www.uefa.com/rssfeed/news/rss.xml",
                "description": "All news about European football.",
                "itemInfo": {
                    "tagName": "item",
                    "title": { "tagName": "title", "attributeName": "", "prefix": "" },
                    "subtitle": { "tagName": "pubDate", "attributeName": "", "prefix": "Date: " },
                    "description": { "tagName": "author", "attributeName": "", "prefix": "Author: " },
                    "content": { "tagName": "description", "attributeName": "", "prefix": "" },
                    "moreInfo": { "tagName": "link", "attributeName": "" },
                    "image": { "tagName": "enclosure", "attributeName": "url" }
                }
            },
            errorItem: {
                group: {
                    key: "0",
                    title: "Error in Rss settings",
                    subtitle: "Try fix your RSS settings from the AppBar!",
                    description: 'Go to AppBar, choose RSS settings, fix the incorrect url, tagName or attributeName and then press "Save and Go!" button.',
                    backgroundImage: getRandomColor(),
                    url: "",
                },
                title: "Error in Rss settings",
                subtitle: "Try fix your RSS settings from the AppBar!",
                description: 'Go to AppBar, choose Settings and fix your RSS settings and then press "Save and Go!" button.',
                content: 'In order to connect properly to an RSS you should provide correct RSS Url, and correct names of RSS tags and attribute for each item and info in the RSS that you want to visualize!',
                moreInfo: "",
                backgroundImage: getRandomColor(),
            }
        }),
    });

    Data.Manager.refreshRSS();

    // Get a reference for an item, using the group key and item title as a
    // unique reference to the item that can be easily serialized.
    function getItemReference(item) {
        return [item.group.key, item.title];
    }

    // This function returns a WinJS.Binding.List containing only the items
    // that belong to the provided group.
    function getItemsFromGroup(group) {
        return list.createFiltered(function (item) { return item.group.key === group.key; });
    }

    // Get the unique group corresponding to the provided group key.
    function resolveGroupReference(key) {
        for (var i = 0; i < groupedItems.groups.length; i++) {
            if (groupedItems.groups.getAt(i).key === key) {
                return groupedItems.groups.getAt(i);
            }
        }
    }

    // Get a unique item from the provided string array, which should contain a
    // group key and an item title.
    function resolveItemReference(reference) {
        for (var i = 0; i < groupedItems.length; i++) {
            var item = groupedItems.getAt(i);
            if (item.group.key === reference[0] && item.title === reference[1]) {
                return item;
            }
        }
    }

    function getTagString(prefixTagAttr, parentRssItem) {
        return new WinJS.Promise(function (complete, error, progress) {

            try{
                var resultString = "";
                if (prefixTagAttr.prefix) {
                    resultString += prefixTagAttr.prefix;
                }

                var tag = parentRssItem;

                if (prefixTagAttr.tagName) {
                    tag = parentRssItem.querySelectorAll(prefixTagAttr.tagName)[0];
                }

                if (prefixTagAttr.attributeName) {
                    resultString += tag.attributes.getNamedItem(prefixTagAttr.attributeName).textContent;
                }
                else if (tag != parentRssItem) {
                    resultString += tag.textContent;
                }

                complete(resultString);
            }
            catch (e) {
                //error("Couldn't load string from tag: " + e);
            }
            complete("");
        });
    }

    function getRandomColor() {
        var colors = [
        "",
        "",
        ""
        ];

        return colors[parseInt(Math.random() * colors.length)];
    }

    function getItems(group) {
        return new WinJS.Promise(function (complete, error, progress) {
            WinJS.xhr({ url: group.url }).then(
            function (rss) {
                try{
                    var rssItems = rss.responseXML.querySelectorAll(group.itemInfo.tagName);

                    var resultItems = [];

                    for (var i = 0; i < rssItems.length; i += 1) {
                        var item = {};

                        item.group = group;

                        getTagString(group.itemInfo.title, rssItems[i])
                            .then(function (str) { item.title = str; });

                        getTagString(group.itemInfo.subtitle, rssItems[i])
                            .then(function (str) { item.subtitle = str; });

                        getTagString(group.itemInfo.description, rssItems[i])
                            .then(function (str) { item.description = str; });

                        getTagString(group.itemInfo.content, rssItems[i])
                            .then(function (str) { item.content = str; });

                        getTagString(group.itemInfo.moreInfo, rssItems[i])
                            .then(function (str) { item.moreInfo = str; });

                        getTagString(group.itemInfo.image, rssItems[i])
                            .then(function (str) { item.backgroundImage = str || getRandomColor() });

                        resultItems.push(item);
                    }

                    complete(resultItems);
                }
                catch (e) {
                    error("Couldn't load RSS! " + e);
                }
            },
            function (err) {
                error("Couldn't load RSS! " + err);
            });
        });
    }
    
    function generateData() {
        
        return new WinJS.Promise(function (complete, error, progress) {

            var group = Settings.Manager.getRoamingSettings();

            getItems(group).then(
                function (itms) {
                    complete(itms);
                },
                function (er) {
                    error(er);
                });
        });
    }

})();